/**
 * jims
 */
package com.jims.master.modules.doctor.web;

import com.jims.master.common.data.StringData;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.web.BaseController;
import com.jims.master.modules.csm.entity.ExpStock;
import com.jims.master.modules.doctor.entity.OutpTreatRec;
import com.jims.master.modules.doctor.service.OutpTreatRecService;
import com.jims.master.modules.sys.entity.PerformFreqDict;
import com.jims.master.modules.sys.entity.SysOrgDict;
import com.jims.master.modules.sys.utils.PerformFreqUtils;
import com.jims.master.modules.sys.utils.SysOrgDictUtils;
import com.jims.master.modules.sys.utils.UserUtils;
import com.jims.master.modules.template.entity.DoctorTempla;
import com.jims.master.modules.template.entity.TreatProjectItem;
import com.jims.master.modules.template.entity.TreatRecordItem;
import com.jims.master.modules.template.service.DoctorTemplaService;
import com.jims.master.modules.template.service.TreatProjectItemService;
import com.jims.master.modules.template.service.TreatRecordItemService;
import com.jims.master.modules.utils.TemplateTreeTable;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 处置治疗Controller
 * @author 陈晓阳
 * @version 2017-03-14
 */
@Controller
@RequestMapping(value = "${adminPath}/doctor/outpTreatRec")
public class OutpTreatRecController extends BaseController {

	@Autowired
	private OutpTreatRecService outpTreatRecService;
	@Autowired
	private DoctorTemplaService doctorTemplaService;
	@Autowired
	private TreatProjectItemService treatProjectItemService;
	@Autowired
	private TreatRecordItemService treatRecordItemService;
	
	@ModelAttribute
	public OutpTreatRec get(@RequestParam(required=false) String id) {
		OutpTreatRec entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = outpTreatRecService.get(id);
		}
		if (entity == null){
			entity = new OutpTreatRec();
		}
		return entity;
	}

    /**
     * 跳转处置治疗页面
     * @param outpTreatRec
     * @param request
     * @param response
     * @param model
     * @return
     * @Author 陈晓阳
     */
	@RequiresPermissions("user")
	@RequestMapping(value = {"index", ""})
	public String list(OutpTreatRec outpTreatRec, HttpServletRequest request, HttpServletResponse response, Model model) {
		UserUtils userUtils = new UserUtils();
		model.addAttribute("creator",userUtils.getUser().getId());
		model.addAttribute("billingDept",userUtils.getUser().getOrgDept().getId());
        //过滤处置治疗
        String[] stringArray = {"E","J","K","F","G","Z","C","D"};
        outpTreatRec.setItemClassFilter(stringArray);
		//查询这个病人已开的处置治疗
        Page<OutpTreatRec> page = outpTreatRecService.findPage(new Page<OutpTreatRec>(request, response), outpTreatRec);
		model.addAttribute("page", page);
        model.addAttribute("outpTreatRec", outpTreatRec);
		return "modules/doctor/treat/outpTreatRecIndex";
	}


    /**
     * 材料申请页面
     * @param outpTreatRec
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"material", ""})
    public String material(OutpTreatRec outpTreatRec, HttpServletRequest request, HttpServletResponse response, Model model) {
        UserUtils userUtils = new UserUtils();
        model.addAttribute("creator",userUtils.getUser().getId());
        model.addAttribute("billingDept",userUtils.getUser().getOrgDept().getId());
        //过滤处置治疗是材料的
        String[] stringArray = {"I"};
        outpTreatRec.setItemClassFilter(stringArray);
        //查询这个病人已开的材料
        Page<OutpTreatRec> page = outpTreatRecService.findPage(new Page<OutpTreatRec>(request, response), outpTreatRec);
        model.addAttribute("page", page);
        model.addAttribute("outpTreatRec", outpTreatRec);
        return "modules/doctor/treat/outpTreatRecMaterialIndex";
    }


	/**
	 * 治疗模板主页
	 * @param doctorTempla
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = {"indexTreat", ""})
	public String indexTreat(DoctorTempla doctorTempla,String title,String type,String visitId,String clinicId,String patientId,String prescApplyId,String itemClass,String inoroutFlag, HttpServletRequest request, HttpServletResponse response, Model model) {
		UserUtils userUtils = new UserUtils();
		doctorTempla.setCreatr(userUtils.getUser().getId());
		doctorTempla.setProjectType(type);
        doctorTempla.setItemClass(itemClass);
		List<DoctorTempla> page = doctorTemplaService.findListTable(doctorTempla);
//		model.addAttribute("creatr",userUtils.getUser().getId());
		model.addAttribute("pageApply", page);
		model.addAttribute("clinicId", clinicId);
		model.addAttribute("patientId", patientId);
		model.addAttribute("visitId", visitId);
		if("0".equals(type)){
			return "modules/doctor/treat/template/treatTemplaIndex";
		}
		else if("1".equals(type)){
			return "modules/orders/orderTemplate/orderTemplaIndex";
		} else if("2".equals(type)){
			model.addAttribute("inoroutFlag",inoroutFlag);
			model.addAttribute("prescApplyId",prescApplyId);
			model.addAttribute("itemClass",itemClass);
			return "modules/doctor/prescription/templatePresc/prescTemplaIndex";
		} else {
			TreatRecordItem treatRecordItem = new TreatRecordItem();
			model.addAttribute("treatRecordItem",treatRecordItem);
			return "modules/doctor/recordTemplaIndex";
		}

	}



	@RequiresPermissions("user")
	@RequestMapping(value = {"indexTreatSub", ""})
	public String indexTreatSub(TreatProjectItem treatProjectItem,String itemClass,TreatRecordItem treatRecordItem,String id,String type, HttpServletRequest request, HttpServletResponse response, Model model) {
		List<TreatProjectItem> treeList = new ArrayList<TreatProjectItem>();
		treatProjectItem.setApplyId(id);

		List<TreatProjectItem> list = treatProjectItemService.findList(treatProjectItem);
//		Page<TreatProjectItem> page = treatProjectItemService.findPage(new Page<TreatProjectItem>(request, response), treatProjectItem);
		if(("2".equals(type) && "A".equals(itemClass)) || "1".equals(type)){
			treeList =new TemplateTreeTable(list).buildTree();
			if(treeList.size()==0){
				treeList=list;
			}
		}
		model.addAttribute("treeList", treeList);
		model.addAttribute("applyId",id);
		if("0".equals(type)){
			model.addAttribute("list", list);
			return "modules/doctor/treat/template/treatProjectItemBottom";
		} else if("1".equals(type)){
			return "modules/orders/orderTemplate/orderProjectItemBottom";
		} else if("2".equals(type)){
            if("A".equals(itemClass)){
                return "modules/doctor/prescription/templatePresc/prescProjectItemBottom";
            } else {
                List<SysOrgDict> administrationDicts = SysOrgDictUtils.getSysDictList("ADMINISTRATION_DICT");
//                List<SysOrgDict> clinicDict = SysOrgDictUtils.getSysDictList("CLINIC_DICT");
                model.addAttribute("administrationDicts", administrationDicts);
                List<PerformFreqDict> frequency = PerformFreqUtils.findFreqList();
                model.addAttribute("frequency", frequency);
                if(list.size()!= 0){
                    model.addAttribute("channel", list.get(0).getAdministration());
                    model.addAttribute("frequency1", list.get(0).getPerformFreq());
                }
                model.addAttribute("chinaList", list);
                return "modules/doctor/prescription/templatePresc/prescChineseItem";
            }

		} else {
			treatRecordItem.setApplyId(id);
			List<TreatRecordItem> listRecord = treatRecordItemService.findList(treatRecordItem);
			if(listRecord.size()>0){
				treatRecordItem = listRecord.get(0);
			}
			model.addAttribute("treatRecordItem", treatRecordItem);
			return "modules/doctor/recordProjectItemBottom";
		}
	}

	/**
	 *
	 * @param id
	 * @param clinicId
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "saveTreatTemplate")
	@ResponseBody
	public StringData saveTreatTemplate(String id,String clinicId,String patientId,OutpTreatRec outpTreatRec){
		StringData data=new StringData();
		String i=outpTreatRecService.saveTreatTemplate(id,clinicId,patientId,outpTreatRec.getOutpTreatRecs());
		if(i!=null){
			data.setCode("success");
			data.setData("保存处置治疗成功");
		}else{
			data.setCode("error");
			data.setData("保存处置治疗失败");
		}
		return data;
	}



    /**
     * 打开右侧页面
     * @param outpTreatRec
     * @param model
     * @return
     */
	@RequiresPermissions("user")
	@RequestMapping(value = "form")
	public String form(OutpTreatRec outpTreatRec, Model model) {
		model.addAttribute("outpTreatRec", outpTreatRec);
		return "modules/doctor/treat/outpTreatRecForm";
	}
    /**
     * 打开右侧页面
     * @param outpTreatRec
     * @param model
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "formMaterial")
    public String formMaterial(OutpTreatRec outpTreatRec, Model model) {
        model.addAttribute("outpTreatRec", outpTreatRec);
        return "modules/doctor/treat/outpTreatRecMaterialForm";
    }
	@RequiresPermissions("user")
	@RequestMapping(value = "save")
	@ResponseBody
	public StringData save(OutpTreatRec outpTreatRec, Model model) {
 	    StringData data=new StringData();
		String i=outpTreatRecService.saveOutpTreatRec(outpTreatRec);
        if(i!=null){
            data.setCode("success");
            data.setData("保存成功");
        }else{
            data.setCode("error");
            data.setData("保存失败");
        }
        return data;
	}
	@RequiresPermissions("user")
	@RequestMapping(value = "delete")
	@ResponseBody
	public StringData delete(OutpTreatRec outpTreatRec) {
	    StringData data=new StringData();
		int i=outpTreatRecService.delete(outpTreatRec);
        if(i>0){
            data.setCode("success");
            data.setData("删除处置治疗成功");
        }else{
            data.setCode("error");
            data.setData("删除处置治疗失败");
        }
		return data;
	}

    /**
     * 获取已收费待发放的患者列表，按开单时间排序
     * @param outpTreatRec
     * @param model
     * @return
     * @Author ZhuQ
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "findByExp")
    public String findByExp(OutpTreatRec outpTreatRec, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<OutpTreatRec> page = outpTreatRecService.findByExp(new Page<OutpTreatRec>(request, response), outpTreatRec);
        model.addAttribute("page", page);
        model.addAttribute("outpTreatRec", outpTreatRec);
        return "modules/drugOut/expPrescOutIndex";
    }

    /**
     * 点击获取待发消耗品list
     * @param outpTreatRec
     * @param model
     * @return
     * @Author ZhuQ
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "expOutList")
    public String expOutList(OutpTreatRec outpTreatRec, HttpServletRequest request, HttpServletResponse response, Model model) {
        List<ExpStock> expStockList = outpTreatRecService.expOutList(outpTreatRec);
        Double sum=0.0;
        for (int i=0;i<expStockList.size();i++){
            sum=sum + expStockList.get(i).getQuantity()*expStockList.get(i).getPurchasePrice();
        }
        ExpStock expStock =new ExpStock();
        DecimalFormat df = new DecimalFormat("#.00");
        sum= Double.valueOf(df.format(sum));
        expStock.setPurchasePrice(sum);
        List<ExpStock> allPriceList = new ArrayList<>();
        allPriceList.add(expStock);
        model.addAttribute("expStockList", expStockList);
        model.addAttribute("allPriceList", allPriceList);
        return "modules/drugOut/expPrescOutForm";
    }

    /**
     * 点击获取已发过的消耗品list
     * @param outpTreatRec
     * @param model
     * @return
     * @Author ZhuQ
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "expGiveOutList")
    public String expGiveOutList(OutpTreatRec outpTreatRec, HttpServletRequest request, HttpServletResponse response, Model model) {
        List<ExpStock> expStockList = outpTreatRecService.expGiveOutList(outpTreatRec);
        Double sum=0.0;
        for (int i=0;i<expStockList.size();i++){
            sum=sum + expStockList.get(i).getQuantity()*expStockList.get(i).getPurchasePrice();
        }
        ExpStock expStock =new ExpStock();
        expStock.setPurchasePrice(sum);
        List<ExpStock> allPriceList = new ArrayList<>();
        allPriceList.add(expStock);
        model.addAttribute("expStockList", expStockList);
        model.addAttribute("allPriceList", allPriceList);
        return "modules/drugOut/expPrescRecordClinicForm";
    }


    /**
     * 点击获取待发消耗品list
     * @param outpTreatRec
     * @param model
     * @return
     * @Author ZhuQ
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "clinicExpOut")
    @ResponseBody
    public StringData clinicExpOut(@RequestBody OutpTreatRec outpTreatRec, HttpServletRequest request, HttpServletResponse response, Model model) {
        StringData data=new StringData();
        String i=outpTreatRecService.clinicExpOut(outpTreatRec);
        if ("1".equals(i)) {
            data.setCode("success");
            data.setData("发放成功");
        } else if ("0".equals(i)) {
            data.setCode("error");
            data.setData("发放失败");
        } else {
            data.setCode("quantity");
            data.setData(i + "库存量不足");
        }
        return data;
    }

    /**
     * 获取消耗品已发放的患者列表，按开单时间排序
     * @param outpTreatRec
     * @param model
     * @return
     * @Author ZhuQ
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "findByOutExp")
    public String findByOutExp(OutpTreatRec outpTreatRec, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<OutpTreatRec> page = outpTreatRecService.findByOutExp(new Page<OutpTreatRec>(request, response), outpTreatRec);
        model.addAttribute("page", page);
        model.addAttribute("outpTreatRec", outpTreatRec);
        return "modules/drugOut/expPrescRecordClinicIndex";
    }

    /**
     * @param outpTreatRec 传递参数
     * @return StringData    返回类型
     * @Desciption: 门诊处方退药
     * @author ZhuQ
     * @date 2017-03-21
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "clinicExpIn")
    @ResponseBody
    public StringData clinicExpIn(OutpTreatRec outpTreatRec) {
        StringData data = new StringData();
        String i = outpTreatRecService.clinicExpIn(outpTreatRec);
        if ("1".equals(i)) {
            data.setCode("success");
            data.setData("门诊消耗品退货成功");
        } else if ("0".equals(i)) {
            data.setCode("error");
            data.setData("门诊消耗品退货失败");
        } else {
            data.setCode("error");
            data.setData(i + "库存量不足");
        }
        return data;
    }
    /**
     * 处置治疗单打印
     * @param
     * @return
     * @author fd
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"outpTreatRecPrint", ""})
    @ResponseBody
    public StringData outpTreatRecPrint(String ids,String clinicId,String patientId){
        StringData stringData = new StringData();
        String printPath =outpTreatRecService.outpTreatRecPrint(ids,clinicId,patientId);
        stringData.setCode("success");
        stringData.setData(printPath);
        return stringData;
    }
}